﻿using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.User;
using System.Transactions;
using Microsoft.Extensions.Logging;
using RBAC.Domain.RBAC;

namespace RBAC.Write.Api.Application.Handler.User
{
    public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, APIResult<int>>
    {
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly IBaseRepository<UserRoleModel> userRoleRepository;
        private readonly ILogger<DeleteUserHandler> logger;

        public DeleteUserHandler(IBaseRepository<UserModel> userRepository, IBaseRepository<UserRoleModel> userRoleRepository, ILogger<DeleteUserHandler> logger)
        {
            this.userRepository = userRepository;
            this.userRoleRepository = userRoleRepository;
            this.logger = logger;
        }
        
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            
            try
            {
                logger.LogInformation("开始删除用户，用户ID: {UserId}", request.Id);
                
                // 1. 检查用户是否存在
                var user = userRepository.GetFirstOrDefault("Id = @Id AND IsDeleted = false", new { Id = request.Id });
                if (user == null)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "用户不存在或已被删除";
                    logger.LogWarning("用户不存在或已被删除，ID: {UserId}", request.Id);
                    return Task.FromResult(res);
                }
                
                logger.LogInformation("找到用户: {UserName} (ID: {UserId})", user.UserName, user.Id);
                
                using (TransactionScope tran = new TransactionScope())
                {
                    try
                    {
                        // 2. 软删除用户角色关联
                        var userRoles = userRoleRepository.GetAll("UserId = @UserId AND IsDeleted = false", new { UserId = request.Id });
                        logger.LogInformation("找到 {UserRoleCount} 个用户角色关联", userRoles.Count);
                        
                        foreach (var userRole in userRoles)
                        {
                            userRole.IsDeleted = true;
                            var updateResult = userRoleRepository.Update(userRole);
                            logger.LogInformation("软删除用户角色关联: UserId={UserId}, RoleId={RoleId}, 结果={Result}", 
                                userRole.UserId, userRole.RoleId, updateResult);
                        }
                        
                        // 3. 软删除用户本身
                        user.IsDeleted = true;
                        var userUpdateResult = userRepository.Update(user);
                        logger.LogInformation("软删除用户结果: {Result}", userUpdateResult);
                        
                        tran.Complete();
                        
                        res.Code = APIEnums.Success;
                        res.Msg = "用户删除成功";
                        res.Data = userUpdateResult;
                        
                        logger.LogInformation("用户 {UserName} (ID: {UserId}) 删除完成", user.UserName, user.Id);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "删除用户过程中发生错误: {Message}", ex.Message);
                        res.Code = APIEnums.Error;
                        res.Msg = "删除用户失败";
                        res.Data = 0;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除用户失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "删除用户失败";
                res.Data = 0;
            }

            return Task.FromResult(res);
        }
    }
}
